<template>
    <div class="enforcement-container">
        <el-card>
            <template #header>
                <div class="card-header">
                    <span>执法处理</span>
                    <div class="header-actions">
                        <el-input
                            v-model="searchQuery"
                            placeholder="请输入地点"
                            clearable
                            style="width: 200px; margin-right: 10px;"
                            @keyup.enter="handleSearch"
                        />
                        <!-- <el-select v-model="statusFilter" placeholder="处理状态" style="width: 120px; margin-right: 10px;"
                            clearable @change="handleSearch">
                            <el-option label="未读" value="0" />
                            <el-option label="已读" value="1" />
                        </el-select> -->
                        <el-select v-model="violationTypeFilter" placeholder="违法类型" style="width: 150px; margin-right: 10px;"
                            clearable @change="handleSearch">
                            <el-option 
                                v-for="type in violationTypeOptions" 
                                :key="type.id" 
                                :label="type.type" 
                                :value="type.id" 
                            />
                        </el-select>
                        <el-date-picker
                            v-model="dateRange"
                            type="datetimerange"
                            range-separator="至"
                            start-placeholder="开始时间"
                            end-placeholder="结束时间"
                            format="YYYY-MM-DD HH:mm:ss"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            style="margin-right: 10px;"
                        />
                        <el-button type="primary" @click="handleSearch">搜索</el-button>
                        <el-button type="success" @click="handleExport">导出</el-button>
                    </div>
                </div>
            </template>

            <el-table :data="tableData" v-loading="loading" border style="width: 100%">
                <el-table-column prop="id" label="案件编号" width="120" />
                <el-table-column prop="carId" label="车牌号" width="120" />
                <el-table-column prop="violationType" label="违法类型" width="120">
                    <template #default="{ row }">
                        <el-tag :type="getViolationTag(row.violationType)">
                            {{ getViolationTypeName(row.violationType) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="违法时间" width="180">
                    <template #default="{ row }">
                        {{ formatDateTime(row.createTime) }}
                    </template>
                </el-table-column>
                <el-table-column prop="location" label="违法地点" width="180" />
                <el-table-column prop="status" label="处理状态" width="120">
                    <template #default="{ row }">
                        <el-tag :type="getStatusTag(row.status)">
                            {{ getStatusName(row.status) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200" fixed="right">
                    <template #default="{ row }">
                        <el-button 
                            type="primary" 
                            link 
                            @click="handleView(row)"
                        >
                            查看详情
                        </el-button>
                        <el-button 
                            v-if="row.status === '0'"
                            type="success" 
                            link 
                            @click="handleProcess(row)"
                        >
                            处理
                        </el-button>
                        <el-button 
                            type="danger" 
                            link 
                            @click="handleDelete(row)"
                        >
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
                    :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </el-card>

        <el-dialog v-model="processDialogVisible" :title="`处理案件 - ${currentCase.id}`" width="60%">
            <case-process :caseData="currentCase" @submit="handleSubmitProcess"
                @cancel="processDialogVisible = false" />
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { 
  getExecutionPage, 
  updateExecution,
  deleteExecution,
  addExecution
} from '../api/enforcement'
import {
    getEmployeeById
} from  '../api/employee'

import{

} from '../api/violation'
import { formatDateTime } from '@/utils/date'
import CaseProcess from '../components/CaseProcess.vue'
import { ElMessage } from 'element-plus'

const route = useRoute()
const searchQuery = ref('')
const statusFilter = ref('')
const violationTypeFilter = ref('')
const tableData = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const processDialogVisible = ref(false)
const currentCase = ref({})
const violationTypeOptions = ref([])
const dateRange = ref([])

// 状态映射
const statusMap = {
  '0': '未读',
  '1': '已读'
}

// 违法类型标签颜色
const typeColorMap = {
  '1': 'danger',
  '2': 'warning',
  '3': 'info',
  '4': 'primary',
  '5': 'success'
}
const statusColorMap ={
    '0': 'danger',
    '1':  'success'
}

// 默认违法类型映射
const defaultViolationTypeMap = {
  1: '超速',
  2: '未按导向行驶',
  3: '车辆压线',
  4: '车辆闯红灯',
  5: '行人闯红灯'
}

// 获取违法类型名称
const getViolationTypeName = (typeId) => {
  const type = violationTypeOptions.value.find(item => item.id === typeId)
  return type ? type.type : (defaultViolationTypeMap[typeId] || '未知类型')
}

// 获取状态名称
const getStatusName = (status) => {
  return statusMap[status] || '未知状态'
}

// 获取违法类型标签
const getViolationTag = (type) => {
  return typeColorMap[type] || 'info'
}

// 获取状态标签
const getStatusTag = (status) => {
  return statusColorMap[status] || 'info'
}

// 加载违法类型选项
const loadViolationTypes = async () => {
  try {
    // 由于没有提供获取违法类型的API，使用默认选项
    violationTypeOptions.value = [
      { id: 1, type: '超速' },
      { id: 2, type: '未按导向行驶' },
      { id: 3, type: '车辆压线' },
      { id: 4, type: '车辆闯红灯' },
      { id: 5, type: '行人闯红灯' }
    ]
  } catch (error) {
    console.error('加载违法类型失败:', error)
    // 使用默认选项
    violationTypeOptions.value = [
      { id: 1, type: '超速' },
      { id: 2, type: '未按导向行驶' },
      { id: 3, type: '车辆压线' },
      { id: 4, type: '车辆闯红灯' },
      { id: 5, type: '行人闯红灯' }
    ]
  }
}

// 检查是否有待处理的违法记录
const checkPendingCase = async () => {
  const id = route.query.id
  const type = route.query.type
  const fromViolation = route.query.fromViolation
  
  if (id && type === 'process' && fromViolation === 'true') {
    try {
      // 使用分页查询API获取单条记录
      const params = {
        page: 1,
        pageSize: 1,
        ids: [id]
      }
      const res = await getExecutionPage(params)
      if (res.code === 1 && res.data.records && res.data.records.length > 0) {
        const caseData = res.data.records[0]
        currentCase.value = {
          id: caseData.id,
          car_id: caseData.carId || '无法识别', // 修改这里，使用carId字段
          violationType: caseData.violationType,
          violationTypeName: getViolationTypeName(caseData.violationType),
          violationTime: caseData.createTime,
          location: caseData.location || '未知位置',
          status: getStatusName(caseData.status),
          description: caseData.detail || '',
          evidenceImages: caseData.imagePath ? [caseData.imagePath] : [],
          originalData: caseData
        }
        processDialogVisible.value = true
      } else {
        ElMessage.error('获取案件详情失败: ' + (res.msg || '未找到案件'))
      }
    } catch (error) {
      console.error('获取案件详情失败:', error)
      ElMessage.error('获取案件详情失败')
    }
  }
}

// 获取数据
const fetchData = async () => {
    try {
        loading.value = true
        
        // 构建请求参数，只发送后端支持的参数
        const params = {
            page: currentPage.value,
            pageSize: pageSize.value
        }
        
        // 添加违法类型筛选
        if (violationTypeFilter.value) {
            params.violationType = violationTypeFilter.value
        }
        
        // 将搜索改为按地点搜索
        if (searchQuery.value && searchQuery.value.trim()) {
            params.location = searchQuery.value.trim()
        }
        
        // // 如果有状态筛选
        // if (statusFilter.value) {
        //     params.status = statusFilter.value
        // }
        
        // 如果有时间范围，添加时间参数
        if (dateRange.value && dateRange.value.length === 2) {
            params.beginTime = dateRange.value[0]
            params.endTime = dateRange.value[1]
        }
        
        console.log('请求参数:', params)
        
        // 使用 getExecutionPage API
        const response = await getExecutionPage(params)
        
        if (response.code) {
            tableData.value = response.data.records || []
            total.value = response.data.total || 0
            console.log('获取执法案件成功:', response.data)
        } else {
            console.error('获取执法案件失败:', response.msg)
            ElMessage.error(response.msg || '获取执法案件失败')
            tableData.value = []
            total.value = 0
        }
    } catch (error) {
        console.error('获取执法案件失败:', error)
        ElMessage.error('获取执法案件失败')
        tableData.value = []
        total.value = 0
    } finally {
        loading.value = false
    }
}

// 搜索
const handleSearch = () => {
    currentPage.value = 1
    fetchData()
}

// 分页处理
const handleSizeChange = (val) => {
    pageSize.value = val
    currentPage.value = 1
    fetchData()
}

const handleCurrentChange = (val) => {
    currentPage.value = val
    fetchData()
}

// 查看详情
const handleView = async (row) => {
    try {
        console.log('查看详情，行数据:', row);
        // 使用分页查询API获取单条记录
        const params = {
            page: 1,
            pageSize: 1,
            ids: [row.id]
        }
        console.log('请求参数:', params);
        const res = await getExecutionPage(params)
        console.log('获取案件详情响应:', res);
        if (res.code === 1 && res.data.records && res.data.records.length > 0) {
            const caseData = res.data.records[0]
            currentCase.value = {
                id: caseData.id,
                car_id: caseData.carId || '无法识别', // 修改这里，使用carId字段
                violationType: caseData.violationType,
                violationTypeName: getViolationTypeName(caseData.violationType),
                violationTime: caseData.createTime,
                location: caseData.location || '未知位置',
                status: getStatusName(caseData.status),
                description: caseData.detail || '',
                evidenceImages: caseData.imagePath ? [caseData.imagePath] : [],
                originalData: caseData
            }
            processDialogVisible.value = true
        } else {
            console.error('获取案件详情失败，响应数据:', res);
            ElMessage.error('获取案件详情失败: ' + (res.msg || '未找到案件'))
        }
    } catch (error) {
        console.error('获取案件详情失败:', error)
        ElMessage.error('获取案件详情失败')
    }
}

// 处理案件
const handleProcess = async (row) => {
    await handleView(row)
}

// 删除案件
const handleDelete = async (row) => {
    try {
        await deleteExecution(row.id)
        ElMessage.success('删除成功')
        await fetchData()
    } catch (error) {
        console.error('删除失败:', error)
        ElMessage.error('删除失败')
    }
}

// 提交处理结果
const handleSubmitProcess = async (processData) => {
    try {
        loading.value = true
        
        const updateData = {
            id: currentCase.value.id,
            status: processData.status,
            detail: processData.comments // 使用detail字段存储处理意见
        }
        
        await updateExecution(updateData)
        
        ElMessage.success('案件处理成功')
        processDialogVisible.value = false
        await fetchData()
        
    } catch (error) {
        console.error('处理案件失败:', error)
        ElMessage.error('处理案件失败，请重试')
    } finally {
        loading.value = false
    }
}

// 导出数据
const handleExport = async () => {
    
        try {
            loading.value = true;
            ElMessage.info('正在准备导出数据，请稍候...');
            
            // 构建请求参数，获取所有符合条件的数据
            const params = {
                page: 1,
                pageSize: 1000,  // 获取较大数量的数据用于导出
                violationType: violationTypeFilter.value || undefined,
                location: searchQuery.value && searchQuery.value.trim() ? searchQuery.value.trim() : undefined
            };
            
            // 如果有时间范围，添加时间参数
            if (dateRange.value && dateRange.value.length === 2) {
                params.beginTime = dateRange.value[0];
                params.endTime = dateRange.value[1];
            }
            
            console.log('导出请求参数:', params);
            
            // 使用 getExecutionPage API 获取数据
            const response = await getExecutionPage(params);
            
            if (response.code !== 200 || !response.data || !response.data.records) {
                throw new Error('获取导出数据失败: ' + (response.msg || '未知错误'));
            }
            
            // 动态导入xlsx库
            const XLSX = await import('xlsx');
            
            // 将数据转换为Excel格式
            const data = response.data.records.map(item => ({
                '案件编号': item.id,
                '车牌号': item.carId || '无法识别',
                '违法类型': getViolationTypeName(item.violationType),
                '违法时间': formatDateTime(item.createTime),
                '违法地点': item.location || '未知位置',
                '处理状态': getStatusName(item.status),
                '详情': item.detail || ''
            }));
            
            // 创建工作表
            const worksheet = XLSX.utils.json_to_sheet(data);
            
            // 设置列宽
            const columnWidths = [
                { wch: 10 },  // 案件编号
                { wch: 12 },  // 车牌号
                { wch: 12 },  // 违法类型
                { wch: 20 },  // 违法时间
                { wch: 30 },  // 违法地点
                { wch: 10 },  // 处理状态
                { wch: 40 }   // 详情
            ];
            worksheet['!cols'] = columnWidths;
            
            // 创建工作簿
            const workbook = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(workbook, worksheet, '执法记录');
            
            // 生成文件名，包含当前日期
            const fileName = `执法记录_${new Date().toISOString().slice(0, 10)}.xlsx`;
            
            // 导出Excel文件
            XLSX.writeFile(workbook, fileName);
            
            ElMessage.success('导出成功');
        } catch (error) {
            console.error('导出失败:', error);
            ElMessage.error('导出失败: ' + error.message);
        } finally {
            loading.value = false;
        }
    
};
onMounted(async () => {
    await loadViolationTypes()
    await fetchData()
    await checkPendingCase()
})
</script>

<style scoped>
.enforcement-container {
    padding: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-actions {
    display: flex;
    align-items: center;
}

.pagination {
    margin-top: 20px;
    display: flex;
    justify-content: center;
}
</style>
